import tkinter as tk
from tkinter import messagebox


# 计算等比数列和的函数
def geometric_sequence_sum(a, r, n):
    if r == 1:
        return a * n
    return a * (1 - r ** n) / (1 - r) if r != 0 else a


# 创建等比数列计算窗口的函数
def switch_to_geometric_sequence(window):
    # 隐藏主窗口
    window.withdraw()
    geo_window = tk.Toplevel()
    geo_window.title("等比数列求和")
    geo_window.geometry("400x350")

    tk.Label(geo_window, text="首项 (a):").pack()
    entry_a_geo = tk.Entry(geo_window)
    entry_a_geo.pack()

    tk.Label(geo_window, text="公比 (r):").pack()
    entry_r_geo = tk.Entry(geo_window)
    entry_r_geo.pack()

    tk.Label(geo_window, text="项数 (n):").pack()
    entry_n_geo = tk.Entry(geo_window)
    entry_n_geo.pack()

    result_label = tk.Label(geo_window, text="", wraplength=400)
    result_label.pack()

    def calculate_geometric():
        try:
            a = float(entry_a_geo.get())
            r = float(entry_r_geo.get())
            n = int(entry_n_geo.get())
            result = geometric_sequence_sum(a, r, n)
            result_label.config(text=f"等比数列的和是: {result}")
        except ValueError:
            messagebox.showerror("错误", "请输入合适的数字")

    # 创建等比数列求和的按钮
    calculate_button = tk.Button(geo_window, text="等比数列求和", command=calculate_geometric)
    calculate_button.pack()

    # 创建返回按钮，点击后关闭等比数列求和窗口并恢复主窗口
    return_button = tk.Button(geo_window, text="返回", command=lambda: [geo_window.destroy(), window.deiconify()])
    return_button.pack()